package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.*;
import com.acme.bankapp.domain.bank.exceptions.ClientExistsException;

import java.io.*;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;

/**
 * Created by anton on 8/22/14.
 */
public class BankDataLoaderService {
    public static void loadBank(Bank bank, File file) {
        try(BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            String line = null;
            while((line = bf.readLine()) != null) {
//                Client client = parseClient(line);
                bank.addClient(parseClient(line));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClientExistsException e) {
            e.printStackTrace();
        }
    }

    private static Client parseClient(String line) {
        String name = null;
        double balance = 0, overdraft = 0;
        Gender gender = null;
        String acctype = null;

        StringTokenizer tokenizer1 = new StringTokenizer(line, ";");
//        System.out.println(tokenizer1.nextToken());
        while (tokenizer1.hasMoreTokens()) {
            StringTokenizer tokenizer2 = new StringTokenizer(tokenizer1.nextToken(), "=");
            String key = tokenizer2.nextToken();
            String value = tokenizer2.nextToken();
            switch (key) {
                case "accounttype":
                    acctype = value;
                    break;
                case "balance":
                    balance = Double.parseDouble(value);
                    break;
                case "overdraft":
                    overdraft = Double.parseDouble(value);
                    break;
                case "name":
                    name = value;
                    break;
                case "gender":
                    if (value.equals("m")) {
                        gender = Gender.MALE;
                    } else {
                        gender = Gender.FEMALE;
                    }
            }
        }
        if (acctype.equals("c")) {
            return new Client(name, gender, new CheckingAccount(balance, overdraft));
        } else {
            return new Client(name, gender, new SavingsAccount(balance));
        }
    }

    public static void main(String[] args) {
        Bank b = new Bank();
        File f = new File("/Users/anton/Developer/javaSchool/feed/feed");
        loadBank(b, f);

    }
}
